package com.huizhonglm.diap.ui.user;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bruce.common.ActivityMgr;
import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.Status;
import com.huizhonglm.diap.api.model.user.ChecksumResponse;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.presenters.user.ChecksumPresenter;
import com.huizhonglm.diap.presenters.user.FinishUserInfoPresenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.iView.ChecksumIView;
import com.huizhonglm.diap.ui.user.iView.FinishUserInfoIView;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-03 10:53
 */
public class FinishUserInfoActivity extends BaseActivity implements ChecksumIView,
        FinishUserInfoIView, View.OnClickListener {

    private EditText nameEdt;
    private EditText phoneEdt;
    private EditText idcardEdt;
    private EditText checkSumEdt;
    private TextView getChecksumTxt;
    private String checksum;

    /**
     * 是否开始计时
     */
    private boolean isStarted = false;
    /**
     * 最大时间(60秒)
     */
    private int time = 60;
    /**
     * 计时器
     */
    private Timer timer;
    /**
     * 计时器线程
     */
    private TimerTask task;
    /**
     * 消息处理器
     */
    private TimerHandler timerHandler;

    private ChecksumPresenter checksumPresenter;

    private FinishUserInfoPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMgr.getInstance().pushActivity(FinishUserInfoActivity.this);
        setContentView(R.layout.activity_finish_user_info);
        setBackEvent(this, null);
        timerHandler = new TimerHandler(this);
        checksumPresenter = new ChecksumPresenter(this);
        mPresenter = new FinishUserInfoPresenter(this);
        assignViews();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTimer();
    }

    @Override
    protected void assignViews(){
        nameEdt = (EditText) findViewById(R.id.name_edt);
        phoneEdt = (EditText) findViewById(R.id.phone_num_edt);
        idcardEdt = (EditText) findViewById(R.id.idcard_num_edt);
        checkSumEdt = (EditText) findViewById(R.id.check_sum_edt);
        getChecksumTxt = (TextView) findViewById(R.id.get_checksum_txt);
        View submitBtn = findViewById(R.id.submit_btn);
        submitBtn.setOnClickListener(this);
        getChecksumTxt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String phone = phoneEdt.getText().toString();
        switch (v.getId()){
            case R.id.submit_btn:
                String name = nameEdt.getText().toString();
                String idcard = idcardEdt.getText().toString();
                if (EmptyUtil.isEmpty(name)){
                    ToastUtil.makeTextShort("请输入姓名");
                    return;
                }
                if (EmptyUtil.isEmpty(idcard)){
                    ToastUtil.makeTextShort("请输入身份证号");
                    return;
                } else {
                    if (idcard.length() < 18) {
                        ToastUtil.makeTextShort("输入的身份证号无效");
                    }
                }
                if (EmptyUtil.isEmpty(phone)){
                    ToastUtil.makeTextShort("请输入手机号码");
                    return;
                } else {
                    if (phone.length() < 11) {
                        ToastUtil.makeTextShort("输入的手机号码无效");
                    }
                }
                if (EmptyUtil.isEmpty(checksum)){
                    ToastUtil.makeTextShort("请获取手机验证码");
                    return;
                }
                if (EmptyUtil.isEmpty(checkSumEdt.getText())){
                    ToastUtil.makeTextShort("请输入手机验证码");
                    return;
                }
                if (!checkSumEdt.getText().toString().equals(checksum)) {
                    ToastUtil.makeTextShort("验证码错误");
                    return;
                }
                showProgressBar();
                mPresenter.onSubmit(name, idcard, phone, checksum);
                break;
            case R.id.get_checksum_txt:
                if (EmptyUtil.isEmpty(phone)){
                    ToastUtil.makeTextShort("请输入手机号码");
                    return;
                } else {
                    if (phone.length() < 11) {
                        ToastUtil.makeTextShort("输入的手机号码无效");
                    }
                }
                phoneEdt.setEnabled(false);
                getChecksum(phone);
                break;
        }
    }

    @Override
    public void onSubmitSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("信息完善成功");
        finish();
    }

    @Override
    public void onSubmitFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("信息完善失败");
    }

    @Override
    public void onChecksumSuccess(ChecksumResponse resp) {
        hideProgressBar();
        if (resp != null) {
            switch (resp.getStatus()){
                case Status.SUCCESS:
                    checksum = resp.getChekCode();
                    break;
                case Status.HAS_REG:
                    stopTimer();
                    ToastUtil.makeTextShort("该账号已被注册，请直接登录");
                    break;
                case Status.FAILURE:
                    stopTimer();
                    ToastUtil.makeTextShort("验证码获取失败，请稍后重试");
                    break;
            }
        }
    }

    @Override
    public void onChecksumFailure() {
        phoneEdt.setEnabled(true);
        hideProgressBar();
        stopTimer();
        ToastUtil.makeTextShort("验证码获取失败");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void getChecksum(String phoneNumber){
        showProgressBar();
        startTimer();
        checksumPresenter.getChecksum(phoneNumber, "N");
    }

    private void startTimer() {
        if (!isStarted) {
            isStarted = true;
            getChecksumTxt.setEnabled(false);
            getChecksumTxt.setTextColor(ContextCompat.getColor(this, R.color.darkGray));
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    timerHandler.sendEmptyMessage(0);
                }
            };
            timer.schedule(task, 0, 1000);
        }
    }

    private void stopTimer() {
        if (isStarted) {
            isStarted = false;
            getChecksumTxt.setEnabled(true);
            getChecksumTxt.setText("重新获取");
            getChecksumTxt.setTextColor(ContextCompat.getColor(this, R.color.mainRed));
            if (timer != null && task != null) {
                timer.cancel();
                timer.purge();
                task.cancel();
                task = null;
                timer = null;
            }
        }
    }

    /**
     * 处理消息
     *
     * @param msg 消息
     */
    private void updateTimer(Message msg) {
        switch (msg.what) {
            case 0:
                String text = "*秒后可重新获取";
                if (time > 1) {
                    time--;
                    text = text.replace("*", time + "");
                } else {
                    stopTimer();
                    text = "重新获取";
                    time = 60;
                }
                getChecksumTxt.setText(text);
                break;
        }
    }

    /**
     * 消息处理器
     *
     * @author uthor LiXiaoLong
     * @since 2013-6-18 下午3:56:24
     */
    private static class TimerHandler extends Handler {
        WeakReference<FinishUserInfoActivity> activity;

        public TimerHandler(FinishUserInfoActivity acti) {
            activity = new WeakReference<>(acti);
        }

        @Override
        public void handleMessage(Message msg) {
            FinishUserInfoActivity theActivity = activity.get();
            theActivity.updateTimer(msg);
        }
    }

}
